<?php
require_once 'relationDeletor.php';

class relation_has_and_belongs_to_manyDeletor extends relationDeletor 
{
    
    
    public static function delete(Datatype_relation_has_and_belongs_to_many $fObj)
    {
        static $nestedLevel = 0;
        
       
       if($opposite = $fObj->getOpposite() AND $nestedLevel == 0)
       {
           $nestedLevel++;
           $opposite = explode('_', $opposite, 2);
           
           $oppObj = $fObj->getOwner()->getHandler()->get($fObj->getClassName());
           
           
           
           $oppRel = $oppObj->getFieldObject($opposite[1]);
           
           
           
           $card = $fObj->getOwner()->getHandler()->get('member_card');
           
           $args = array(array('objectname', '=', $oppRel->getOwner()->getClass()));
           
           $cards = $card->getFinder()->findAll($args);
                   
           
           
           
           
           
           
           $grid = $fObj->getOwner()->getHandler()->get('member_grid');

           $args = array(
           array('member_card_edoid', 'IN', implode(',', $cards->getKeys())),
           array('fieldname', '=', $oppRel->getName()),
           );
           
           $grid = $grid->getFinder()->findFirst($args);
           
           if($grid)
                $grid->delete();     
                
           $oppRel->getOwner()->dropField($oppRel->getName());
           
           
           $fObj->getOwner()->ldb->exec("DROP TABLE {$fObj->getJoinTable()}");
                                
           $nestedLevel--; 
       }
        
        $deletor = parent::delete($fObj);
        
        if(!$deletor)
            return false;

      
       return true;
       
    }
    
    
    
}